package org.wheel.plugins.toolkit.sql.render;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;

import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * 问号参数渲染
 */
public final class QuestionRender implements ParamRenderStrategy {

    private final List<Object> orderedParams = CollUtil.newArrayList();
    private final Map<String, Object> paramMap;

    public QuestionRender(Map<String, Object> paramMap) {
        this.paramMap = paramMap;
    }

    @Override
    public String render(String sql) {
        return ReUtil.replaceAll(sql, ":(\\w+)", m -> {
            String key = m.group(1);
            Object value = paramMap.get(key);
            orderedParams.add(paramMap.get(m.group(1)));
            if(value instanceof Collection<?> col){
                String[] colArray = StrUtil.repeat("?,", col.size()).split(",");
                return StrUtil.join(", ", List.of(colArray));
            }
            return "?";
        });
    }

    @Override
    public Object getParamObject() {
        return orderedParams;
    }

    @Override
    public Map<String, Object> getParamMap() {
        return paramMap;
    }
}